<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>04 Mybatis 缓存的实现原理 - 暗夜零星</title><meta name="Description" content="mybatis 缓存模块的实现，源码分析。"><meta property="og:title" content="04 Mybatis 缓存的实现原理" />
<meta property="og:description" content="mybatis 缓存模块的实现，源码分析。" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://wlizhi.cc/posts/mybatis/04-mybatis-cache/" /><meta property="og:image" content="https://wlizhi.cc/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2020-12-30T17:08:55+08:00" />
<meta property="article:modified_time" content="2020-12-30T17:08:55+08:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://wlizhi.cc/logo.png"/>

<meta name="twitter:title" content="04 Mybatis 缓存的实现原理"/>
<meta name="twitter:description" content="mybatis 缓存模块的实现，源码分析。"/>
<meta name="application-name" content="暗夜零星">
<meta name="apple-mobile-web-app-title" content="暗夜零星"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://wlizhi.cc/posts/mybatis/04-mybatis-cache/" /><link rel="prev" href="https://wlizhi.cc/posts/mybatis/03-mybatis-pooled-data-source/" /><link rel="next" href="https://wlizhi.cc/posts/concurrent/reentrant-distributed-lock/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "04 Mybatis 缓存的实现原理",
        "inLanguage": "",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/wlizhi.cc\/posts\/mybatis\/04-mybatis-cache\/"
        },"genre": "posts","keywords": "mybatis源码","wordcount":  2861 ,
        "url": "https:\/\/wlizhi.cc\/posts\/mybatis\/04-mybatis-cache\/","datePublished": "2020-12-30T17:08:55+08:00","dateModified": "2020-12-30T17:08:55+08:00","publisher": {
            "@type": "Organization",
            "name": "Wlizhi"},"author": {
                "@type": "Person",
                "name": "Wlizhi"
            },"description": "mybatis 缓存模块的实现，源码分析。"
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="暗夜零星"><span class="header-title-pre"><i class='far fa-moon fa-fw'></i></span>暗夜零星</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 所有文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><a class="menu-item" href="/message-board/"> 留言 </a><a class="menu-item" href="/about/"> 关于 </a><a class="menu-item" href="https://github.com/wlizhi" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i>  </a><a class="menu-item" href="https://gitee.com/wlizhi" title="Gitee" rel="noopener noreffer" target="_blank"><i class='fab fa-git fa-fw'></i>  </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="点击搜索..." id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="暗夜零星"><span class="header-title-pre"><i class='far fa-moon fa-fw'></i></span>暗夜零星</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="点击搜索..." id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">所有文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><a class="menu-item" href="/message-board/" title="">留言</a><a class="menu-item" href="/about/" title="">关于</a><a class="menu-item" href="https://github.com/wlizhi" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i></a><a class="menu-item" href="https://gitee.com/wlizhi" title="Gitee" rel="noopener noreffer" target="_blank"><i class='fab fa-git fa-fw'></i></a><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <i class="fas fa-adjust fa-fw"></i>
            </a></div>
    </div>
</header>
<div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div>
<main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">04 Mybatis 缓存的实现原理</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="https://wlizhi.cc" title="Author" target="_blank" rel="noopener noreffer author" class="author"><i class="fas fa-user-circle fa-fw"></i>Wlizhi</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/mybatis/"><i class="far fa-folder fa-fw"></i>mybatis</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2020-12-30">2020-12-30</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2861 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 6 分钟&nbsp;<span id="/posts/mybatis/04-mybatis-cache/" class="leancloud_visitors" data-flag-title="04 Mybatis 缓存的实现原理">
                        <i class="far fa-eye fa-fw"></i>&nbsp;<span class=leancloud-visitors-count></span>&nbsp;次阅读
                    </span>&nbsp;</div>
        </div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#1-缓存模块概要">1 缓存模块概要</a></li>
    <li><a href="#2-装饰器模式">2 装饰器模式</a></li>
    <li><a href="#3-缓存key的创建方式---cachekey">3 缓存key的创建方式 - CacheKey</a></li>
    <li><a href="#4-一级缓存">4 一级缓存</a></li>
    <li><a href="#5-二级缓存">5 二级缓存</a></li>
    <li><a href="#6-小结">6 小结</a></li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><p>mybatis源码系列文章，示例中带有中文注释的源码 copy 自 <a href="https://gitee.com/wlizhi/mybatis-3" target="_blank" rel="noopener noreffer">https://gitee.com/wlizhi/mybatis-3</a></p>
<p>链接中源码是作者从 github 下载，并以自身理解对核心流程及主要节点做了详细的中文注释。</p>
<hr>
<h2 id="1-缓存模块概要">1 缓存模块概要</h2>
<ol>
<li>mybatis 的缓存模块是基于 Map 的，从缓存中读写数据是其基础功能。</li>
<li>mybatis 提供了许多缓存的实现。如阻塞式缓存、先进先出缓存、日志缓存、缓存清空策略、软引用缓存、虚引用缓存、具有同步控制的缓存等。</li>
<li>这些缓存实现可以任意的组合优雅的附加到基础功能上。</li>
</ol>
<p>如果使用继承、或动态代理的方式很难做到任意的组合（会有大量子类）。继承或动态代理方式在实现类的组合上来说是静态的，这是 mybatis 缓存模块实现的最大难题。
使用装饰器模式可以解决此问题，mybatis 正是使用了装饰器模式实现的缓存模块。</p>
<h2 id="2-装饰器模式">2 装饰器模式</h2>
<p>意图：动态地给一个对象添加一些额外的职责。就增加功能来说，装饰器模式相比生成子类更为灵活。</p>
<p>主要解决：一般的，我们为了扩展一个类经常使用继承方式实现，由于继承为类引入静态特征，并且随着扩展功能的增多，子类会很膨胀。</p>
<p>何时使用：在不想增加很多子类的情况下扩展类。</p>
<p>如何解决：将具体功能职责划分，同时继承装饰者模式。</p>
<p>使用场景： 1、扩展一个类的功能。 2、动态增加功能，动态撤销。</p>
<p>jdk 中 io 流就是典型的装饰器模式。</p>
<p>类似这样：<code>new BufferedInputStream(new FileInputStream(&quot;xx.txt&quot;))</code></p>
<p>使用装饰类，持有原始类的方式，对其进行功能增强。如果需要多层的装饰，则创建装饰实例，然后作为参数传递给下一个装饰实例即可。
这样可以做到任意个数、任意顺序的装饰。装饰本身即是功能的增强。装饰类本身与原始类实现同一个接口/继承了同一个类。</p>
<p>上面示例中，BufferedInputStream、FileInputStream 实际上都实现了 InputStream。</p>
<p>Collections 类，对集合进行增强的一些静态方法，也是使用了装饰器模式。</p>
<h2 id="3-缓存key的创建方式---cachekey">3 缓存key的创建方式 - CacheKey</h2>
<p>CacheKey 是对 mybatis 缓存的 key 值的封装。由于缓存时的 key 是根据多种元素来生成 key 的，这里需要通过一定的算法来进行封装，
生成 hashcode 和 equals。其中关键方法有 update()、hashCode()、equals()。</p>
<p>源码如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span><span class="lnt">65
</span><span class="lnt">66
</span><span class="lnt">67
</span><span class="lnt">68
</span><span class="lnt">69
</span><span class="lnt">70
</span><span class="lnt">71
</span><span class="lnt">72
</span><span class="lnt">73
</span><span class="lnt">74
</span><span class="lnt">75
</span><span class="lnt">76
</span><span class="lnt">77
</span><span class="lnt">78
</span><span class="lnt">79
</span><span class="lnt">80
</span><span class="lnt">81
</span><span class="lnt">82
</span><span class="lnt">83
</span><span class="lnt">84
</span><span class="lnt">85
</span><span class="lnt">86
</span><span class="lnt">87
</span><span class="lnt">88
</span><span class="lnt">89
</span><span class="lnt">90
</span><span class="lnt">91
</span><span class="lnt">92
</span><span class="lnt">93
</span><span class="lnt">94
</span><span class="lnt">95
</span><span class="lnt">96
</span><span class="lnt">97
</span><span class="lnt">98
</span><span class="lnt">99
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CacheKey</span> <span class="kd">implements</span> <span class="n">Cloneable</span><span class="o">,</span> <span class="n">Serializable</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">long</span> <span class="n">serialVersionUID</span> <span class="o">=</span> <span class="n">1146682552656046210L</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">DEFAULT_MULTIPLIER</span> <span class="o">=</span> <span class="n">37</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">DEFAULT_HASHCODE</span> <span class="o">=</span> <span class="n">17</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="cm">/** 参与 hash 计算的乘数 */</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">multiplier</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="cm">/** CacheKey 的 hash 值，在 update 函数中运算出来的 */</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kt">int</span> <span class="n">hashcode</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="cm">/** 校验和，hash值的和 */</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kt">long</span> <span class="n">checksum</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="cm">/** 参与计算元素的个数 */</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="kt">int</span> <span class="n">count</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="c1">// 8/21/2017 - Sonarlint flags this as needing to be marked transient. While true if content is not serializable, this
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>  <span class="c1">// is not always true and thus should not be marked transient.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>  <span class="cm">/** 该集合中的元素决定两个 CacheKey 是否相等 */</span>
</span></span><span class="line"><span class="cl">  <span class="kd">private</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">&gt;</span> <span class="n">updateList</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="nf">CacheKey</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">this</span><span class="o">.</span><span class="na">hashcode</span> <span class="o">=</span> <span class="n">DEFAULT_HASHCODE</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="k">this</span><span class="o">.</span><span class="na">multiplier</span> <span class="o">=</span> <span class="n">DEFAULT_MULTIPLIER</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="k">this</span><span class="o">.</span><span class="na">count</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="k">this</span><span class="o">.</span><span class="na">updateList</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="nf">CacheKey</span><span class="o">(</span><span class="n">Object</span><span class="o">[]</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">this</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="n">updateAll</span><span class="o">(</span><span class="n">objects</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="kt">int</span> <span class="nf">getUpdateCount</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">updateList</span><span class="o">.</span><span class="na">size</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">update</span><span class="o">(</span><span class="n">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// 获取object的hash值
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="kt">int</span> <span class="n">baseHashCode</span> <span class="o">=</span> <span class="n">object</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">?</span> <span class="n">1</span> <span class="o">:</span> <span class="n">ArrayUtil</span><span class="o">.</span><span class="na">hashCode</span><span class="o">(</span><span class="n">object</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// 更新count、checksum以及hashcode的值
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="n">count</span><span class="o">++;</span>
</span></span><span class="line"><span class="cl">    <span class="n">checksum</span> <span class="o">+=</span> <span class="n">baseHashCode</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="n">baseHashCode</span> <span class="o">*=</span> <span class="n">count</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">hashcode</span> <span class="o">=</span> <span class="n">multiplier</span> <span class="o">*</span> <span class="n">hashcode</span> <span class="o">+</span> <span class="n">baseHashCode</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// 将对象添加到updateList中
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="n">updateList</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">object</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">updateAll</span><span class="o">(</span><span class="n">Object</span><span class="o">[]</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="o">(</span><span class="n">Object</span> <span class="n">o</span> <span class="o">:</span> <span class="n">objects</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="n">update</span><span class="o">(</span><span class="n">o</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">equals</span><span class="o">(</span><span class="n">Object</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// 比较是不是同一个对象
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(</span><span class="k">this</span> <span class="o">==</span> <span class="n">object</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="kc">true</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// 是否类型相同
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(!(</span><span class="n">object</span> <span class="k">instanceof</span> <span class="n">CacheKey</span><span class="o">))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="kd">final</span> <span class="n">CacheKey</span> <span class="n">cacheKey</span> <span class="o">=</span> <span class="o">(</span><span class="n">CacheKey</span><span class="o">)</span> <span class="n">object</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// hashcode 是否相同
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(</span><span class="n">hashcode</span> <span class="o">!=</span> <span class="n">cacheKey</span><span class="o">.</span><span class="na">hashcode</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// checksum 是否相同
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(</span><span class="n">checksum</span> <span class="o">!=</span> <span class="n">cacheKey</span><span class="o">.</span><span class="na">checksum</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// count是否相同
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(</span><span class="n">count</span> <span class="o">!=</span> <span class="n">cacheKey</span><span class="o">.</span><span class="na">count</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// 以上都相同，才按顺序比较 updateList 中元素是否相等，只有全部相等，才返回 true。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">updateList</span><span class="o">.</span><span class="na">size</span><span class="o">();</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">      <span class="n">Object</span> <span class="n">thisObject</span> <span class="o">=</span> <span class="n">updateList</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">      <span class="n">Object</span> <span class="n">thatObject</span> <span class="o">=</span> <span class="n">cacheKey</span><span class="o">.</span><span class="na">updateList</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">      <span class="k">if</span> <span class="o">(!</span><span class="n">ArrayUtil</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">thisObject</span><span class="o">,</span> <span class="n">thatObject</span><span class="o">))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">      <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">true</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">  <span class="kd">public</span> <span class="kt">int</span> <span class="nf">hashCode</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">hashcode</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">  <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>CacheKey 是通过 MapperStatement 的id、offset、limit、以及 sql 中占位符的参数。来计算出对应的 hashcode，并且会将这些信息封装在一个 List 中。</p>
<p>在进行比较的时候，会先进行 hashcode、checksum 的比较，之后对封装的列表中的元素依次比较，如果全部相等，返回true，中途有一个比较不成立，则返回false。</p>
<p>这么做是为了提高效率。</p>
<p>hashcode 和 checkSum 的生成，是根据 updateList 中的元素计算的。</p>
<p>关键的成员变量：</p>
<ol>
<li>hashcode：CacheKey 的 hash 值，在 update 函数中实时运算出来的</li>
<li>checksum：校验和，hash值的和</li>
<li>count：参与计算元素的个数</li>
<li>updateList：该集合中的元素决定两个 CacheKey 是否相等</li>
</ol>
<p>cacheKey 的创建源码如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">BaseExecutor</span> <span class="kd">implements</span> <span class="n">Executor</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">	<span class="kd">public</span> <span class="n">CacheKey</span> <span class="nf">createCacheKey</span><span class="o">(</span><span class="n">MappedStatement</span> <span class="n">ms</span><span class="o">,</span> <span class="n">Object</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">RowBounds</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">BoundSql</span> <span class="n">boundSql</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="o">(</span><span class="n">closed</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">throw</span> <span class="k">new</span> <span class="n">ExecutorException</span><span class="o">(</span><span class="s">&#34;Executor was closed.&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 创建缓存 key
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">CacheKey</span> <span class="n">cacheKey</span> <span class="o">=</span> <span class="k">new</span> <span class="n">CacheKey</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// id、limit、sql等属性，计算 hash值，生成 cacheKey。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">ms</span><span class="o">.</span><span class="na">getId</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">rowBounds</span><span class="o">.</span><span class="na">getOffset</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">rowBounds</span><span class="o">.</span><span class="na">getLimit</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">boundSql</span><span class="o">.</span><span class="na">getSql</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 如果存在参数映射，将参数也加入cacheKey的生成元素中。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">List</span><span class="o">&lt;</span><span class="n">ParameterMapping</span><span class="o">&gt;</span> <span class="n">parameterMappings</span> <span class="o">=</span> <span class="n">boundSql</span><span class="o">.</span><span class="na">getParameterMappings</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">		<span class="n">TypeHandlerRegistry</span> <span class="n">typeHandlerRegistry</span> <span class="o">=</span> <span class="n">ms</span><span class="o">.</span><span class="na">getConfiguration</span><span class="o">().</span><span class="na">getTypeHandlerRegistry</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// mimic DefaultParameterHandler logic
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">for</span> <span class="o">(</span><span class="n">ParameterMapping</span> <span class="n">parameterMapping</span> <span class="o">:</span> <span class="n">parameterMappings</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="o">(</span><span class="n">parameterMapping</span><span class="o">.</span><span class="na">getMode</span><span class="o">()</span> <span class="o">!=</span> <span class="n">ParameterMode</span><span class="o">.</span><span class="na">OUT</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">Object</span> <span class="n">value</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">				<span class="n">String</span> <span class="n">propertyName</span> <span class="o">=</span> <span class="n">parameterMapping</span><span class="o">.</span><span class="na">getProperty</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">				<span class="k">if</span> <span class="o">(</span><span class="n">boundSql</span><span class="o">.</span><span class="na">hasAdditionalParameter</span><span class="o">(</span><span class="n">propertyName</span><span class="o">))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">					<span class="n">value</span> <span class="o">=</span> <span class="n">boundSql</span><span class="o">.</span><span class="na">getAdditionalParameter</span><span class="o">(</span><span class="n">propertyName</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">				<span class="o">}</span> <span class="k">else</span> <span class="k">if</span> <span class="o">(</span><span class="n">parameterObject</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">					<span class="n">value</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">				<span class="o">}</span> <span class="k">else</span> <span class="k">if</span> <span class="o">(</span><span class="n">typeHandlerRegistry</span><span class="o">.</span><span class="na">hasTypeHandler</span><span class="o">(</span><span class="n">parameterObject</span><span class="o">.</span><span class="na">getClass</span><span class="o">()))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">					<span class="n">value</span> <span class="o">=</span> <span class="n">parameterObject</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">				<span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">					<span class="n">MetaObject</span> <span class="n">metaObject</span> <span class="o">=</span> <span class="n">configuration</span><span class="o">.</span><span class="na">newMetaObject</span><span class="o">(</span><span class="n">parameterObject</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">					<span class="n">value</span> <span class="o">=</span> <span class="n">metaObject</span><span class="o">.</span><span class="na">getValue</span><span class="o">(</span><span class="n">propertyName</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">				<span class="o">}</span>
</span></span><span class="line"><span class="cl">				<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">value</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">			<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="o">(</span><span class="n">configuration</span><span class="o">.</span><span class="na">getEnvironment</span><span class="o">()</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="c1">// issue #176
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>			<span class="n">cacheKey</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">configuration</span><span class="o">.</span><span class="na">getEnvironment</span><span class="o">().</span><span class="na">getId</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="n">cacheKey</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">	<span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="4-一级缓存">4 一级缓存</h2>
<p>mybatis 中的缓存是通过 Cache 接口来实现的。它负责存储缓存的 key-value 内容。</p>
<p>一级缓存的生命周期与 sqlSession 相同，即是线程隔离的。它的触发点是在二级缓存之后，也就是说，二级缓存中没有内容时，才会从一级缓存中获取，最后从数据库获取。</p>
<p>在 BaseExecutor 中有成员变量 localCache，这里就保存了一级缓存的内容。</p>
<p>默认的缓存实现类是 PerpetualCache，它通过 HashMap 来存储数据，其数据结构源码如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">PerpetualCache</span> <span class="kd">implements</span> <span class="n">Cache</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="kd">private</span> <span class="kd">final</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Object</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">cache</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>如果我们调用一个查询语句，触发一级缓存的源码如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">BaseExecutor</span> <span class="kd">implements</span> <span class="n">Executor</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">	<span class="kd">public</span> <span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="nf">query</span><span class="o">(</span><span class="n">MappedStatement</span> <span class="n">ms</span><span class="o">,</span> <span class="n">Object</span> <span class="n">parameter</span><span class="o">,</span> <span class="n">RowBounds</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">ResultHandler</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">CacheKey</span> <span class="n">key</span><span class="o">,</span> <span class="n">BoundSql</span> <span class="n">boundSql</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">SQLException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">ErrorContext</span><span class="o">.</span><span class="na">instance</span><span class="o">().</span><span class="na">resource</span><span class="o">(</span><span class="n">ms</span><span class="o">.</span><span class="na">getResource</span><span class="o">()).</span><span class="na">activity</span><span class="o">(</span><span class="s">&#34;executing a query&#34;</span><span class="o">).</span><span class="na">object</span><span class="o">(</span><span class="n">ms</span><span class="o">.</span><span class="na">getId</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 检查当前 executor 是否关闭。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">if</span> <span class="o">(</span><span class="n">closed</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">throw</span> <span class="k">new</span> <span class="n">ExecutorException</span><span class="o">(</span><span class="s">&#34;Executor was closed.&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 非嵌套查询，并且 flushCacheRequired 配置为 true，则需要清空一级缓存。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">if</span> <span class="o">(</span><span class="n">queryStack</span> <span class="o">==</span> <span class="n">0</span> <span class="o">&amp;&amp;</span> <span class="n">ms</span><span class="o">.</span><span class="na">isFlushCacheRequired</span><span class="o">())</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">clearLocalCache</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">list</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">		<span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="c1">// 查询层次 +1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>			<span class="n">queryStack</span><span class="o">++;</span>
</span></span><span class="line"><span class="cl">			<span class="c1">// 查询一级缓存
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>			<span class="n">list</span> <span class="o">=</span> <span class="n">resultHandler</span> <span class="o">==</span> <span class="kc">null</span> <span class="o">?</span> <span class="o">(</span><span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;)</span> <span class="n">localCache</span><span class="o">.</span><span class="na">getObject</span><span class="o">(</span><span class="n">key</span><span class="o">)</span> <span class="o">:</span> <span class="kc">null</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="o">(</span><span class="n">list</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">				<span class="c1">// 针对调用存储过程的结果处理。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>				<span class="n">handleLocallyCachedOutputParameters</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">parameter</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">			<span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">				<span class="c1">// 从数据库查询数据。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>				<span class="n">list</span> <span class="o">=</span> <span class="n">queryFromDatabase</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">parameter</span><span class="o">,</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">			<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">queryStack</span><span class="o">--;</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 其余源码省略...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">return</span> <span class="n">list</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">	<span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>根据 cacheKey 从一级缓存中获取数据，如果存在，直接返回。如果不存在，则从数据库中查询数据。</p>
<h2 id="5-二级缓存">5 二级缓存</h2>
<p>二级缓存存储在 MappedStatement 的变量 cache 中，也就是与 Mapper 文件的封装类实例生命周期一致，是应用级的。</p>
<p>源码如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CachingExecutor</span> <span class="kd">implements</span> <span class="n">Executor</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">	<span class="kd">public</span> <span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="nf">query</span><span class="o">(</span><span class="n">MappedStatement</span> <span class="n">ms</span><span class="o">,</span> <span class="n">Object</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">RowBounds</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">ResultHandler</span> <span class="n">resultHandler</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">SQLException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 获取 sql 语句信息，包括占位符、参数等信息。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">BoundSql</span> <span class="n">boundSql</span> <span class="o">=</span> <span class="n">ms</span><span class="o">.</span><span class="na">getBoundSql</span><span class="o">(</span><span class="n">parameterObject</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 拼装缓存 key 值
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">CacheKey</span> <span class="n">key</span> <span class="o">=</span> <span class="n">createCacheKey</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 执行查询
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">return</span> <span class="n">query</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">	<span class="o">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">	<span class="kd">public</span> <span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="nf">query</span><span class="o">(</span><span class="n">MappedStatement</span> <span class="n">ms</span><span class="o">,</span> <span class="n">Object</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">RowBounds</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">ResultHandler</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">CacheKey</span> <span class="n">key</span><span class="o">,</span> <span class="n">BoundSql</span> <span class="n">boundSql</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">			<span class="kd">throws</span> <span class="n">SQLException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 从 MappedStatement 中获取二级缓存
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="n">Cache</span> <span class="n">cache</span> <span class="o">=</span> <span class="n">ms</span><span class="o">.</span><span class="na">getCache</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="o">(</span><span class="n">cache</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">flushCacheIfRequired</span><span class="o">(</span><span class="n">ms</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="o">(</span><span class="n">ms</span><span class="o">.</span><span class="na">isUseCache</span><span class="o">()</span> <span class="o">&amp;&amp;</span> <span class="n">resultHandler</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">ensureNoOutParams</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                <span class="c1">// 从二级缓存中获取数据。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>				<span class="nd">@SuppressWarnings</span><span class="o">(</span><span class="s">&#34;unchecked&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">				<span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="o">(</span><span class="n">List</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;)</span> <span class="n">tcm</span><span class="o">.</span><span class="na">getObject</span><span class="o">(</span><span class="n">cache</span><span class="o">,</span> <span class="n">key</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">				<span class="k">if</span> <span class="o">(</span><span class="n">list</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">					<span class="c1">// 二级缓存为空，才会调用 BaseExecutor.query()。
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>					<span class="n">list</span> <span class="o">=</span> <span class="n">delegate</span><span class="o">.</span><span class="na">query</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">					<span class="n">tcm</span><span class="o">.</span><span class="na">putObject</span><span class="o">(</span><span class="n">cache</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">list</span><span class="o">);</span> <span class="c1">// issue #578 and #116
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>				<span class="o">}</span>
</span></span><span class="line"><span class="cl">				<span class="k">return</span> <span class="n">list</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">			<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="o">}</span>
</span></span><span class="line"><span class="cl">		<span class="c1">// 执行查询
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>		<span class="k">return</span> <span class="n">delegate</span><span class="o">.</span><span class="na">query</span><span class="o">(</span><span class="n">ms</span><span class="o">,</span> <span class="n">parameterObject</span><span class="o">,</span> <span class="n">rowBounds</span><span class="o">,</span> <span class="n">resultHandler</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">boundSql</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">	<span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>二级缓存和一级缓存 cacheKey 的生成并无区别。仅仅是存储的位置不同，导致其生命周期不同，这是他们最大的区别。</p>
<h2 id="6-小结">6 小结</h2>
<p>一级缓存和二级缓存只是作用范围、生命周期不同。一级缓存是在sqlSession中，查询时保存到缓存、更新时清除缓存。二级缓存是在 MappedStatement 中，更新时会清除对应id的 MappedStatement 中的二级缓存。</p>
<p>二级缓存可能存在跨 MappedStatement 的情况，所以存在一致性问题，一般不使用。</p></div>

        <div id="donateDiv"><a id="donate">打赏</a></div>
<div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2020-12-30</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/mybatis%E6%BA%90%E7%A0%81/">mybatis源码</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/mybatis/03-mybatis-pooled-data-source/" class="prev" rel="prev" title="03 Mybatis 连接池的实现原理"><i class="fas fa-angle-left fa-fw"></i>03 Mybatis 连接池的实现原理</a>
            <a href="/posts/concurrent/reentrant-distributed-lock/" class="next" rel="next" title="自定义分布式可重入锁">自定义分布式可重入锁<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
<div id="comments"><div id="valine" class="comment"></div><noscript>
                Please enable JavaScript to view the comments powered by <a href="https://valine.js.org/">Valine</a>.
            </noscript></div></article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.102.3">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2020 - 2024</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="https://wlizhi.cc" target="_blank">Wlizhi</a></span><span class="icp-splitter">&nbsp;|&nbsp;</span><br class="icp-br"/>
                    <span class="icp"><a href='https://beian.miit.gov.cn/' target='_blank'>豫ICP备17048163号<a/></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="/lib/valine/valine.min.css"><link rel="stylesheet" href="/lib/lightgallery/lightgallery.min.css"><script type="text/javascript" src="/lib/valine/Valine.min.js"></script><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/autocomplete/autocomplete.min.js"></script><script type="text/javascript" src="/lib/algoliasearch/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lightgallery.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lg-thumbnail.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lg-zoom.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":35},"comment":{"valine":{"appId":"4yIHB0Rs1r3ykDVxayI5nqj3-gzGzoHsz","appKey":"ALr4H1hlK94girLDEUCGmp3o","avatar":"mp","el":"#valine","emojiCDN":"https://cdn.jsdelivr.net/npm/emoji-datasource-google@5.0.1/img/google/64/","emojiMaps":{"100":"1f4af.png","alien":"1f47d.png","anger":"1f4a2.png","angry":"1f620.png","anguished":"1f627.png","astonished":"1f632.png","black_heart":"1f5a4.png","blue_heart":"1f499.png","blush":"1f60a.png","bomb":"1f4a3.png","boom":"1f4a5.png","broken_heart":"1f494.png","brown_heart":"1f90e.png","clown_face":"1f921.png","cold_face":"1f976.png","cold_sweat":"1f630.png","confounded":"1f616.png","confused":"1f615.png","cry":"1f622.png","crying_cat_face":"1f63f.png","cupid":"1f498.png","dash":"1f4a8.png","disappointed":"1f61e.png","disappointed_relieved":"1f625.png","dizzy":"1f4ab.png","dizzy_face":"1f635.png","drooling_face":"1f924.png","exploding_head":"1f92f.png","expressionless":"1f611.png","face_vomiting":"1f92e.png","face_with_cowboy_hat":"1f920.png","face_with_hand_over_mouth":"1f92d.png","face_with_head_bandage":"1f915.png","face_with_monocle":"1f9d0.png","face_with_raised_eyebrow":"1f928.png","face_with_rolling_eyes":"1f644.png","face_with_symbols_on_mouth":"1f92c.png","face_with_thermometer":"1f912.png","fearful":"1f628.png","flushed":"1f633.png","frowning":"1f626.png","ghost":"1f47b.png","gift_heart":"1f49d.png","green_heart":"1f49a.png","grimacing":"1f62c.png","grin":"1f601.png","grinning":"1f600.png","hankey":"1f4a9.png","hear_no_evil":"1f649.png","heart":"2764-fe0f.png","heart_decoration":"1f49f.png","heart_eyes":"1f60d.png","heart_eyes_cat":"1f63b.png","heartbeat":"1f493.png","heartpulse":"1f497.png","heavy_heart_exclamation_mark_ornament":"2763-fe0f.png","hole":"1f573-fe0f.png","hot_face":"1f975.png","hugging_face":"1f917.png","hushed":"1f62f.png","imp":"1f47f.png","innocent":"1f607.png","japanese_goblin":"1f47a.png","japanese_ogre":"1f479.png","joy":"1f602.png","joy_cat":"1f639.png","kiss":"1f48b.png","kissing":"1f617.png","kissing_cat":"1f63d.png","kissing_closed_eyes":"1f61a.png","kissing_heart":"1f618.png","kissing_smiling_eyes":"1f619.png","laughing":"1f606.png","left_speech_bubble":"1f5e8-fe0f.png","love_letter":"1f48c.png","lying_face":"1f925.png","mask":"1f637.png","money_mouth_face":"1f911.png","nauseated_face":"1f922.png","nerd_face":"1f913.png","neutral_face":"1f610.png","no_mouth":"1f636.png","open_mouth":"1f62e.png","orange_heart":"1f9e1.png","partying_face":"1f973.png","pensive":"1f614.png","persevere":"1f623.png","pleading_face":"1f97a.png","pouting_cat":"1f63e.png","purple_heart":"1f49c.png","rage":"1f621.png","relaxed":"263a-fe0f.png","relieved":"1f60c.png","revolving_hearts":"1f49e.png","right_anger_bubble":"1f5ef-fe0f.png","robot_face":"1f916.png","rolling_on_the_floor_laughing":"1f923.png","scream":"1f631.png","scream_cat":"1f640.png","see_no_evil":"1f648.png","shushing_face":"1f92b.png","skull":"1f480.png","skull_and_crossbones":"2620-fe0f.png","sleeping":"1f634.png","sleepy":"1f62a.png","slightly_frowning_face":"1f641.png","slightly_smiling_face":"1f642.png","smile":"1f604.png","smile_cat":"1f638.png","smiley":"1f603.png","smiley_cat":"1f63a.png","smiling_face_with_3_hearts":"1f970.png","smiling_imp":"1f608.png","smirk":"1f60f.png","smirk_cat":"1f63c.png","sneezing_face":"1f927.png","sob":"1f62d.png","space_invader":"1f47e.png","sparkling_heart":"1f496.png","speak_no_evil":"1f64a.png","speech_balloon":"1f4ac.png","star-struck":"1f929.png","stuck_out_tongue":"1f61b.png","stuck_out_tongue_closed_eyes":"1f61d.png","stuck_out_tongue_winking_eye":"1f61c.png","sunglasses":"1f60e.png","sweat":"1f613.png","sweat_drops":"1f4a6.png","sweat_smile":"1f605.png","thinking_face":"1f914.png","thought_balloon":"1f4ad.png","tired_face":"1f62b.png","triumph":"1f624.png","two_hearts":"1f495.png","unamused":"1f612.png","upside_down_face":"1f643.png","weary":"1f629.png","white_frowning_face":"2639-fe0f.png","white_heart":"1f90d.png","wink":"1f609.png","woozy_face":"1f974.png","worried":"1f61f.png","yawning_face":"1f971.png","yellow_heart":"1f49b.png","yum":"1f60b.png","zany_face":"1f92a.png","zipper_mouth_face":"1f910.png","zzz":"1f4a4.png"},"enableQQ":true,"highlight":true,"lang":"zh-cn","meta":["nick","mail","link"],"pageSize":5,"placeholder":"昵称栏输入QQ，会使用QQ昵称和头像、并自动补充QQ邮箱到邮箱栏。\r\n正确填写邮箱更容易及时得到回复。\r\n说点什么吧...","recordIP":true,"visitor":true}},"lightGallery":{"actualSize":false,"exThumbImage":"data-thumbnail","hideBarsDelay":2000,"selector":".lightgallery","speed":400,"thumbContHeight":80,"thumbWidth":80,"thumbnail":true},"search":{"algoliaAppID":"1U459KF21F","algoliaIndex":"LoveItSite","algoliaSearchKey":"0433ffe95d71201a4f7c3e04b0125ac5","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script><script type="text/javascript" src="/js/donate.js"></script></body>
</html>
